package com.jf.cloud.service.sysmanager.remote;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.jf.cloud.service.sysmanager.common.util.DateUtil;
import com.jf.cloud.service.sysmanager.common.util.FileUtil;
import com.jf.cloud.service.sysmanager.common.util.JsonUtil;
import com.jf.cloud.service.sysmanager.common.util.MD5;
import com.jf.cloud.service.sysmanager.common.util.StringUtil;
import com.jf.cloud.service.sysmanager.common.util.qnImg.ImgCloud;
import com.jf.cloud.service.sysmanager.constant.ImagePath;
import com.jf.cloud.service.sysmanager.support.entity.PicFile;

/**
 * 富编辑器上传图片
 * 
 * @author 朱建文 创建时间：2017年12月14日 下午2:22:27
 */
@Controller
@RequestMapping("/keUploadImg")
public class KEditUploadImgController {

	/**
	 * 日志
	 */
	private static Log log = LogFactory.getLog(KEditUploadImgController.class);

	/**
	 * 上传文件最大尺寸——2M
	 */
	private final long maxUploadSize = 2 * 1024 * 1024;
	
	@RequestMapping("/uploadImg")
	protected void uploadImg(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile file = multipartRequest.getFile("imgFile"); // 这里不能随便乱改
			if (file == null || file.getSize() == 0) {
				out.println(getErrorMessage("请选择文件。"));
				return;
			}
			
			if (file.getSize() > maxUploadSize) {
				log.info("图片文件太大不能上传");
				out.println(getErrorMessage("上传文件大小超过限制。"));
				return;
			}
			
			String fileName = file.getOriginalFilename(); // 文件名称
			if (StringUtil.isNotEmpty(fileName) && !StringUtil.isImg(fileName)) {
				out.println(getErrorMessage("只允许上传【" + JsonUtil.toJSON(FileUtil.fileSuffixList) + "】类型的文件。"));
				return;
			}
			
			if (fileName.length() <= 2 && !fileName.contains(".")) { // 存在文件
				log.info(" 未知图片名称 或 图片名称 乱码 ");
				out.println(getErrorMessage("未知图片名称 或 图片名称 乱码。"));
				return;
			}
			
			String namekey = MD5.getMessageDigest(fileName.getBytes()).substring(0, 5);
			if (!fileName.contains(".")) { // 乱码的文件名称 需要处理
				if (fileName.length() > 4) {
					String subName = fileName.substring(fileName.length() - 4, fileName.length());
					fileName = "default." + FileUtil.getSuffix(subName);
				} else { // 强制默认一个图片名称
					return;
				}
			}
			
			PicFile pfile = new PicFile();
			pfile.setContent(file.getBytes());
//			ImagePath.T_KE_PIC
			String dateName =  DateUtil.getCurrentDateTime("yyyyMMddHHmmssSSS");
			String fileSuffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
			pfile.setFileName(dateName + namekey + fileSuffix);
			String path = ImagePath.getPath(ImagePath.FOCUS_PATH);
			pfile.setFilePath(path);
			boolean rs = ImgCloud.up(pfile.getFilePath() + pfile.getFileName(), new ByteArrayInputStream(pfile.getContent()));
			if (rs) {
				String imgPath = ImagePath.FOCUS_PATH + pfile.getFilePath() + pfile.getFileName();
				out.println(getMessage("文件上传成功。", imgPath));
			}
		} catch (Exception e) {
			log.error("文件上传失败。", e);
			out.println(getErrorMessage("文件上传失败。"));
		} finally {
			out.flush();
			out.close();
		}
	}

	/**
	 * 获取消息封装
	 * @param message 消息
	 * @param url 文件路径
	 * @return 消息封装
	 * @throws IOException
	 */
	private String getMessage(String message, String url) throws IOException {
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("error", 0);
		obj.put("url", url);
		obj.put("message", message);
		return JsonUtil.toJSON(obj);
	}

	/**
	 * 获取消息封装
	 * @param message 消息
	 * @return 消息封装
	 * @throws IOException
	 */
	private String getErrorMessage(String message) throws IOException {
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("error", 1);
		obj.put("message", message);
		return JsonUtil.toJSON(obj);
	}
	
}
